package com.labelimage.controller;

import cn.hutool.core.util.ReUtil;
import cn.hutool.http.HttpUtil;
import com.labelimage.bean.param.DatasetParam;
import com.labelimage.bean.vo.DatasetVo;
import com.labelimage.common.constant.HttpCode;
import com.labelimage.common.exception.LIException;
import com.labelimage.common.response.Result;
import com.labelimage.common.utils.PageUtils;
import com.labelimage.service.DatasetService;
import com.labelimage.task.AsyncTaskService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("dataset")
@Validated
public class DataSetController {
    @Resource
    private AsyncTaskService asyncTaskService;
    @Resource
    private DatasetService datasetService;


    @PostMapping("")
    public Result<?> create(@RequestBody DatasetParam datasetParam) throws IOException {
        datasetParam.setPath(datasetParam.getPath().trim());
        try {
            String html = HttpUtil.get(datasetParam.getPath());
            List<String> urlList = ReUtil.findAllGroup1("<a href=\".*?\">(.*?)</a>", ReUtil.getGroup1("<pre>(.*?)</pre>", html));
            urlList.remove(0);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LIException("链接不符合标准", HttpCode.INPUT_INFO_ERROR);
        }
        asyncTaskService.createDataset(datasetParam);
        return Result.OK();
    }

    @GetMapping("/{pageNum}")
    public Result<PageUtils<DatasetVo>> load(@PathVariable("pageNum") Integer pageNum) {
        return Result.OK(datasetService.load(pageNum));
    }

    @DeleteMapping("/{datasetId}")
    public Result<PageUtils<DatasetVo>> delete(@PathVariable("datasetId") Long datasetId) throws IOException{
        asyncTaskService.deleteDataset(datasetId);
        return Result.OK();
    }
}
